package cn.yunyichina.provider.framework.qiniu;

import java.io.ByteArrayInputStream;
import java.net.URLEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

/**
 * Created by Lullaby on 2016/8/27.
 */
public class QiniuService {

    private static final Logger logger = LoggerFactory.getLogger(QiniuService.class);

    /**
     * 文件上传
     * @param filePath
     * @param bucket
     * @return
     */
    public static Response upload(String filePath, String key, String bucket) {

        logger.info("[QiniuService.upload.inputParm] filePath:" + filePath + ",key:" +key + ",bucket:" + bucket);

        //创建上传对象华东  Zone.zone0() 华北  Zone.zone1() 华南  Zone.zone2() 北美  Zone.zoneNa0()
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);
        Response res = null;
        try {
            // 调用put方法上传
            res = uploadManager.put(filePath, key, Qiniu.INSTANCE.auth().uploadToken(bucket , key , 2678400 , null));
            // 打印返回的信息
            logger.info("[QiniuService.upload]" + res.bodyString() +"--- statusCode:" + res.statusCode +"--- error:" + res.error);
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            logger.error("[QiniuService.upload.toString]" + r.toString());
            try {
                // 响应的文本信息
                logger.error("[QiniuService.upload.bodyString]" + r.bodyString());
            } catch (QiniuException e1) {
                // ignore
            }
        }

        return res;
    }

    /**
     * 数据流上传
     * @param byteArrayInputStream
     * @param key
     * @param bucket
     * @return
     */
    public static Response upload(ByteArrayInputStream byteArrayInputStream, String key, String bucket) {

        logger.info("[QiniuService.upload.inputParm] key:" + key + ",bucket:" + bucket);

        //创建上传对象华东  Zone.zone0() 华北  Zone.zone1() 华南  Zone.zone2() 北美  Zone.zoneNa0()
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);
        Response res = null;
        try {
            // 调用put方法上传
            res = uploadManager.put(byteArrayInputStream, key, Qiniu.INSTANCE.auth().uploadToken(bucket , key), null, null);
            // 打印返回的信息
            logger.info("[QiniuService.upload]" + res.bodyString() +"--- statusCode:" + res.statusCode +"--- error:" + res.error);
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            logger.error("[QiniuService.upload.toString]" + r.toString());
            try {
                // 响应的文本信息
                logger.error("[QiniuService.upload.bodyString]" + r.bodyString());
            } catch (QiniuException e1) {
                // ignore
            }
        }

        return res;
    }
    
    /**
     * 文件下载
     * @param path 指定文件保存路径
     * @param domainOfBucket
     * @return
     */
    public static String download(String fileName ,String path, String domainOfBucket) {
        String finalUrl = "";
        logger.info("[QiniuService.download.inputParm]" + fileName + ",path: " +path + ",domainOfBucket: " + domainOfBucket);
        try {
            String encodedFileName = URLEncoder.encode(fileName, "utf-8");
            String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
            String accessKey = Qiniu.INSTANCE.ACCESS_KEY;
            String secretKey = Qiniu.INSTANCE.SECRET_KEY;
            logger.info("[QiniuService.download.downloadUrl.Keys] accessKey:" + accessKey + " ------ secretKey:" + secretKey);
            Auth auth = Auth.create(accessKey, secretKey);
            long expireInSeconds = 2678400 ;//1个月，可以自定义链接过期时间
            finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
            logger.info("[QiniuService.download.downloadUrl]" + finalUrl);
        } catch (Exception e) {
            logger.error("[QiniuService.download.bodyString] fileName:" + fileName, e);
        }

        return finalUrl;
    }
}
